import getWeb3 from './getWeb3';
import LoveOnChainContract from '../../build/contracts/LoveOnChain.json';

// 定义用户信息对象
const userInstances = {};

// 初始化Web3
export async function initializeWeb3(userId) {
    if (userInstances[userId]) {
        return userInstances[userId];
    }

    // 获取web3实例
    const web3 = await getWeb3();

    // 使用web3获取用户账户和合约实例
    const accounts = await web3.eth.getAccounts();

    const networkId = await web3.eth.net.getId();
    const deployedNetwork = LoveOnChainContract.networks[networkId];
    const contractInstance = new web3.eth.Contract(
        LoveOnChainContract.abi,
        deployedNetwork && deployedNetwork.address,
    );

    const userInstance = {
        web3,
        accounts,
        contractInstance,
    };

    userInstances[userId] = userInstance;

    return userInstance;
}

//获取我发布的表白卡
export async function getMyCard(userId) {
    try {
        const userInstance = await initializeWeb3(userId);
        const { web3, accounts, contractInstance } = userInstance;
        const result = await contractInstance.methods.getMyCards().call({ from: accounts[0] });
        return result;
    } catch (error) {
        console.log(error);
    }
}

// 发布表白卡
export async function publishCard(userId, to, body, pic) {
    try {
        const userInstance = await initializeWeb3(userId);
        const { contractInstance, accounts } = userInstance;

        // 获取当前时间为string类型
        const currentDateTime = new Date().toISOString();

        // 首先表白对象和表白内容是必填的
        if (!to || !body) {
            return 2; // 返回2表示必填信息缺失
        }

        await contractInstance.methods.createCard(to, body, pic, currentDateTime).send({ from: accounts[0] });

        return 1; // 返回1表示发布成功
    } catch (error) {
        console.log(error);
        return 3; // 返回3表示发布失败
    }
}

// 发布一条评论
export async function publishComment(cardId, info) {
    try {
        const userInstance = await initializeWeb3();
        const { contractInstance, accounts } = userInstance;

        // 获取当前时间为string类型
        const currentDateTime = new Date().toISOString();

        // 评论内容是必填的
        if (!info) {
            return 2; // 返回2表示必填信息缺失
        }

        await contractInstance.methods.addComment(cardId, info, currentDateTime).send({ from: accounts[0] });

        return 1; // 返回1表示发布成功
    } catch (error) {
        console.log(error);
        return 3; // 返回3表示发布失败
    }
}

// 点赞表白卡
export async function likeCard(cardId) {
    try {
        const userInstance = await initializeWeb3();
        const { contractInstance, accounts } = userInstance;

        await contractInstance.methods.addLike(cardId).send({ from: accounts[0] });

        return 1; // 返回1表示点赞成功
    } catch (error) {
        console.log(error);
        return 3; // 返回3表示点赞失败
    }
}

// 取消点赞
export async function unlikeCard(cardId) {
    try {
        const userInstance = await initializeWeb3();
        const { contractInstance, accounts } = userInstance;

        await contractInstance.methods.removeLike(cardId).send({ from: accounts[0] });

        return 1; // 返回1表示取消点赞成功
    } catch (error) {
        console.log(error);
        return 3; // 返回3表示取消点赞失败
    }
}

// 获取所有表白卡信息
export async function getAllCards(userId) {
    try {
        const userInstance = await initializeWeb3(userId);
        const { contractInstance, accounts } = userInstance;

        const cards = await contractInstance.methods.getAllCards().call({ from: accounts[0] });

        return cards; // 返回获取到的所有表白卡信息
    } catch (error) {
        console.log(error);
        return []; // 如果发生错误，返回空数组
    }
}

export async function searchCardsByInfo(keystore) {
    try {
        const userInstance = await initializeWeb3();
        const { contractInstance, accounts } = userInstance;

        const cards = await contractInstance.methods.getCardsByInfo(keystore).call({ from: accounts[0] });

        return cards; // 返回匹配的表白卡信息
    } catch (error) {
        console.log(error);
        throw error; // 抛出错误，而不是返回空数组
    }
}


// 获取评论数量 以及帖子总数 总点赞数量
export async function getStats(userId) {
    try {
        const userInstance = await initializeWeb3(userId);
        const { web3, accounts, contractInstance } = userInstance;

        const result = await contractInstance.methods.getStats().call({ from: accounts[0] });

        // 使用名为 totalCards, totalComments 和 totalLikes 的属性获取数据
        const totalCards = result.totalCards;
        const totalComments = result.totalComments;
        const totalLikes = result.totalLikes;

        return [totalCards, totalComments, totalLikes];
    } catch (error) {
        console.error('An error occurred in getStats:', error);
    }
}

// 获取点赞最多的前三个表白卡
export async function getTopCards(userId) {
    try {
        const userInstance = await initializeWeb3(userId);
        const { contractInstance, accounts } = userInstance;

        const topCards = await contractInstance.methods.getTop3Cards().call({ from: accounts[0] });

        return topCards; // 返回点赞最多的前三个表白卡
    } catch (error) {
        console.log(error);
        return []; // 如果发生错误，返回空数组
    }
}

// 通过ID获取表白卡详情并判断用户对此是否点赞
export async function getCardDetails(cardId) {
    try {
        const userInstance = await initializeWeb3();
        const { contractInstance, accounts } = userInstance;

        const cardDetails = await contractInstance.methods.getCard(cardId).call({ from: accounts[0] });

        return cardDetails; // 返回卡片详情
    } catch (error) {
        console.log(error);
        return null; // 如果发生错误，返回null
    }
}

// 通过ID获取表白卡的所有评论
export async function getCardComments(cardId) {
    try {
        const userInstance = await initializeWeb3();
        const { contractInstance, accounts } = userInstance;

        const cardComments = await contractInstance.methods.getComments(cardId).call({ from: accounts[0] });

        return cardComments; // 返回评论详情
    } catch (error) {
        console.log(error);
        return null; // 如果发生错误，返回null
    }
}